//
//  PageContentView.swift
//  swiftDemo
//
//  Created by Gerry on 2021/11/9.
//

import Foundation
import UIKit

let kCellIdentifier = "kCellIdentifier"

enum ScrollDirection {
    case kDirectionToLeft
    case kDirectionToRight
}

protocol PageContentViewDelegate : AnyObject {
    // scrollDirect 0 左滑， 1 右滑
    func contentOffsetChanged(pageContentView: PageContentView , progress : CGFloat, scrollDirection : ScrollDirection)
}

class PageContentView : UIView {

    private var childVCs : [UIViewController]
    private weak var parentVC : UIViewController?
    private var startX : CGFloat = 0.0
    var delegate : PageContentViewDelegate?
    private var isForbidScroll : Bool = false
    
    private lazy var collectView : UICollectionView = { [weak self] in
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        let cFrame = CGRect.init(x: 0, y: 0, width: (self?.bounds.size.width)!, height: (self?.bounds.size.height)!)
        let collectionView = UICollectionView(frame:cFrame, collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCellIdentifier)
        return collectionView
    }()
    
    init(frame: CGRect, childVCs:[UIViewController], parentVC: UIViewController?) {
        self.childVCs = childVCs
        self.parentVC = parentVC
        
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

extension PageContentView {
    
    private func setupUI() {
        for childVC in self.childVCs {
            self.parentVC?.addChild(childVC)
        }
        
        
        addSubview(collectView)
    }
}

extension PageContentView : UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.childVCs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellIdentifier, for: indexPath)
        
        for subView in cell.contentView.subviews {
            subView.removeFromSuperview()
        }
        
        let vc = self.childVCs[indexPath.row]
        cell.contentView.addSubview(vc.view)
        return cell
    }
}

extension PageContentView {
    func setCurrentPageIndex(index : Int) {
        
        // 点击的tab事件
        isForbidScroll = true
        
        let off = CGFloat(index) * collectView.bounds.width
        collectView.setContentOffset(CGPoint.init(x: off, y: 0), animated: false)
    }
}

extension PageContentView : UICollectionViewDelegate {
    
}


extension PageContentView : UIScrollViewDelegate {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("scrollViewWillBeginDragging offset : \(scrollView.contentOffset.x)")
        isForbidScroll = false
        
        startX = scrollView.contentOffset.x
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        print("scrollViewDidEndDecelerating offset : \(scrollView.contentOffset.x)")
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print("scrollViewDidScroll \(scrollView.contentOffset)")
        if (isForbidScroll) {
            return
        }
        
        var progress = 0.0
        let currentX = scrollView.contentOffset.x
        let offsetX = currentX - startX
        
        if (abs(offsetX) == self.frame.width) {
            progress = offsetX > 0 ? 1 : -1
        } else {
            progress = offsetX / self.frame.width
        }
                
        let scrollDirection : ScrollDirection = (offsetX > 0) ? .kDirectionToLeft : .kDirectionToRight
        delegate?.contentOffsetChanged(pageContentView: self, progress: progress, scrollDirection: scrollDirection)
    }
}
